
package com.youease.chris.action {
	import com.youease.chris.event.ActionEvent;
	
	/**
	 * GroupAction
	 *
	 * @author chris
	 *
	 * Dec 19, 2012
	 */
	public class GroupAction extends BaseAction {
		private var actions:Array;
		private var finishCount:int = 0;
		
		public function GroupAction(actions:Array=null)
		{
			super();
			if(!actions)
				actions = [];
			this.actions = actions;
		}
		
		override public function execute():void {
			super.execute();
			finishCount = 0;
			
			for(var i:int=0; i<actions.length; i++) {
				var action:BaseAction = actions[i] as BaseAction;
				action.addEventListener(ActionEvent.ACTION_COMPLETE,actionCompleteHandler);
				action.addEventListener(ActionEvent.ACTION_ERROR,actionErrorHandler);
				action.execute();
			}
		}
		
		override public function update():void {
			super.update();
			for each(var action:BaseAction in this.actions) {
				action.update();
			}
		}
		
		private function actionCompleteHandler(event:ActionEvent):void
		{
			endAction(event.currentTarget as BaseAction);
		}
		
		private function actionErrorHandler(event:ActionEvent):void
		{
			endAction(event.currentTarget as BaseAction);
		}
		
		private function endAction(action:BaseAction):void
		{
			action.removeEventListener(ActionEvent.ACTION_COMPLETE,actionCompleteHandler);
			action.removeEventListener(ActionEvent.ACTION_ERROR,actionErrorHandler);
			finishCount++;
			
			if (this.actions.length == finishCount)
				complete();
		}
		
		
	}
}